package y.q.h.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import static org.apache.commons.lang3.StringUtils.isBlank;

@Slf4j
public class AESMysql {

    public static final String KEY = "laojiahaowu";

    public static void main(String... args) throws Exception {
        System.out.println("加密1：" + encrpt("小宋"));
        System.out.println("解密1：" + decrpt("AES9C1A7D576D931097F91FD15904B69A23"));
//        System.out.println("解密1："+decrpt("9C1A7D576D931097F91FD15904B69A23"));
//        System.out.println("解密2："+decrpt("B02F333BDE67F38BBF1D5BC53B4D3FC1331900472D355A1EF82CCF4EE0BD4B0080D0505BA894D47EE6F8B1557B646061"));
//        System.out.println("解密3："+decrpt("17C0C5373BE3917C2AC61DADE7A8DA8A"));
    }


    /**
     * AES解密
     *
     * @param data 待解密字符串
     * @return 解密结果
     * @throws Exception 抛出本方法的执行异常
     */
    public static String decrpt(String data) {
        try {
            if (isBlank(data)) {
                return data;
            }
            if (data.startsWith("AES")) {
                data = data.substring(3);
            }
            final Cipher decryptCipher = Cipher.getInstance("AES");
            decryptCipher.init(Cipher.DECRYPT_MODE, generateMySQLAESKey(KEY, StandardCharsets.UTF_8));
            return new String(decryptCipher.doFinal(Hex.decodeHex(data.toCharArray())),
                    StandardCharsets.UTF_8);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("AES解密报错：", e);
        }
        return null;
    }


    /**
     * AES加密
     *
     * @param data 待加密字符串
     * @return 加密结果
     * @throws Exception 抛出本方法的执行异常
     */
    public static String encrpt(String data) {
        try {
            if (isBlank(data)||data.startsWith("AES")) {
                return data;
            }
            final Cipher encryptCipher = Cipher.getInstance("AES");
            encryptCipher.init(Cipher.ENCRYPT_MODE, generateMySQLAESKey(KEY, StandardCharsets.UTF_8));
            char[] code = Hex.encodeHex(encryptCipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));
            StringBuilder builder = new StringBuilder();
            for (char d : code) {
                builder.append(d);
            }
            String upperCase = builder.toString().toUpperCase();
            if (isBlank(upperCase)) {
                return upperCase;
            }
            return "AES" + upperCase;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("AES加密错误", e);
        }
        return null;
    }

    /**
     * 生成AES加解密用的SecretKeySpec
     *
     * @param key     加解密用的秘钥
     * @param charset 编码设置 默认UTF-8
     * @return SecretKeySpec实例
     */
    public static SecretKeySpec generateMySQLAESKey(String key, Charset charset) {
        try {
            final byte[] finalKey = new byte[16];
            int i = 0;
            for (byte b : key.getBytes(charset)) {
                finalKey[i++ % 16] ^= b;
            }
            //System.out.println(new String(finalKey));
            return new SecretKeySpec(finalKey, "AES");
        } catch (Exception e) {
            log.error("执行异常，异常信息：", e);
            return null;
        }
    }
}
